import { loginByUsername, logout, getMenu, getResource, getUserName } from '@/api/login'
import * as api from '@/api/system'
import { myUnreadMessage } from '@/api/notice'
import { Message } from 'element-ui';
import { getToken, setToken, removeToken, getLocalMenu, setLocalMenu, removeLocalMenu, getLocalBtn, setLocalBtn, removeLocalBtn, getName, setName, removeName, getUnread, setUnread } from '@/utils/auth'

function getTree(data, root, idTxt = 'id', pidTxt = 'pid', pushTxt = 'children') {
  let getNode = (id) => {
    let node = []
    data.forEach((val, key, arr) => {
      if (data[key][pidTxt] == id) {
        data[key][pushTxt] = getNode(data[key][idTxt])
        node = [...node, data[key]]
      }
    })
    node.forEach(item => {
      item.children.forEach(childItem => {
        delete childItem.children
      })
    })
    return node.length > 0 ? node : []
  }
  return getNode(root)
}
function getTreeForBtn(data, root, idTxt = 'id', pidTxt = 'pid', pushTxt = 'children') {
  let getNode = (id) => {
    let node = []
    data.forEach((val, key, arr) => {
      if (data[key][pidTxt] == id) {
        data[key][pushTxt] = getNode(data[key][idTxt])
        node = [...node, data[key]]
      }
    })
    return node.length > 0 ? node : []
  }
  return getNode(root)
}
function getTree1(data, data1, root, idTxt = 'id', pidTxt = 'pid', pushTxt = 'children') {
let getNode = (id) => {
  let node = []
  //console.log(data)
  data.forEach((val, key, arr) => {
    if (data[key][pidTxt] == id) {
      var arr = getNode(data[key][idTxt])
      //if (data[key]['type'] != 'ACTION') {
        data[key][pushTxt] = 0 == arr.length ? '' : arr
        if (isExist(data1, data[key][idTxt]) || 0 != data[key][pushTxt].length || 2 == data[key]['id']){
          data[key][pushTxt] = 2 == data[key]['id'] ? [] : (isActionsOrEmpty(arr) ? '' : data[key][pushTxt])
          node = [...node, data[key]]
        }
      //}
    }
  })
  return node.length > 0 ? node : []
}
return getNode(root)
}
function getTree2(data, data1, root, idTxt = 'id', pidTxt = 'pid', pushTxt = 'children') {
 let getNode = (id) => {
   let node = []
   data.forEach((val, key, arr) => {
     if (data[key][pidTxt] == id) {
       var arr = getNode(data[key][idTxt])
       data[key][pushTxt] = 0 == arr.length ? [] : arr
       if (isExist(data1, data[key][idTxt]) || 0 != data[key][pushTxt].length || 2 == data[key]['id']){
         // data[key][pushTxt] = 2 == data[key]['id'] ? [] : data[key][pushTxt]
         node = [...node, data[key]]
       }
     }
   })
   return node.length > 0 ? node : []
 }
 return getNode(root)
}

function isExist(data, id) {
  var b = false
  data.forEach((val, key, arr) => {
    if (id == data[key]['id']) {
      b = true
      return
    }
  })
  return b
}
// 如果传入的数组位按钮组或者为空，则返回True，否则返回false
function isActionsOrEmpty(data) {
  var b = false
  data.forEach((val, key, arr) => {
    b = undefined == data || '' == data || 0 == data.length || data[key]['type'] == 'ACTION' ? true : false
    return
  })
  return b
}

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: getName(),
    unread: getUnread(),
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    menu: getLocalMenu(),
    btn: getLocalBtn()
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_UNREAD: (state, unread) => {
      state.unread = unread
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      // console.log(state.menu)
    },
    SET_BTN: (state, btn) => {
      state.btn = btn
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const account = userInfo.account.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(account, userInfo.psd).then(response => {
          const res = response.data
          if (+res.code === 0) {
          commit('SET_TOKEN', res.data.token)
          setToken(res.data.token)
          commit('SET_NAME', res.data.userName)
          setName(res.data.userName)
          } else if (+res.code === 103) {
            Message.error(res.friendlyMsg)
          } else if (+res.code === 101) {
            Message.error(res.friendlyMsg)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户未读消息
    myUnreadMessage({ commit, state }) {
      return new Promise((resolve, reject) => {
        myUnreadMessage().then((res) => {
          commit('SET_UNREAD', res.data)
          setUnread(res.data)
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    },
    // 动态获取菜单（菜单权限）
    GetMenu({ commit, state }) {
      var data1 = []
      api.resourceList().then((res) => {
        data1 = res.data
        return new Promise((resolve, reject) => {
          getResource().then((res) => {
            var obj = getTree1(data1, res.data, 1, 'id', 'parentId', 'children')
            commit('SET_MENU', window.JSON.stringify(obj))
            setLocalMenu(window.JSON.stringify(obj))
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 动态获取按钮（按钮权限）
    GetBtn({ commit, state }, index) {
      return new Promise((resolve, reject) => {
        var data2 = []
        api.resourceList().then((res) => {
          data2 = res.data
          getResource().then((res) => {
            var obj = getTree2(data2, res.data, 1, 'id', 'parentId', 'children')
            commit('SET_BTN', window.JSON.stringify(obj))
            setLocalBtn(window.JSON.stringify(obj))
            if (index !== undefined || index !== null || index !== '') {
              index()
            }
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_BTN', '')
        commit('SET_MENU', '')
        removeToken()
        removeName()
        removeLocalMenu()
        removeLocalBtn()
        // setLocalMenu('')
        // setLocalBtn('')
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        // getUserInfo(role).then(response => {
        //   const data = response.data
        //   commit('SET_ROLES', data.roles)
        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   resolve()
        // })
      })
    }
     // 获取用户信息
    // GetUserInfo({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     getUserInfo(state.token).then(response => {
    //       if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
    //         reject('error')
    //       }
    //       const data = response.data
    //       commit('SET_ROLES', data.roles)
    //       commit('SET_NAME', data.name)
    //       commit('SET_AVATAR', data.avatar)
    //       commit('SET_INTRODUCTION', data.introduction)
    //       resolve(response)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
  }
}

export default user
